import { ReactElement, Key, useRef, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Modal, Form, FormInstance, Checkbox, message } from 'antd'
import { caseInputRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'

const { Item } = Form

const options = [
  { label: '受理', value: 'accepter_appraisal' },
  { label: '办案', value: 'processer_appraisal' }
]

async function submitHandle (id: string, keys: Key[], types: string[], hide: () => void): Promise<void> {
  const h = message.loading('提交中', 120)
  const [e] = await awaitWrap(caseInputRequest(id, keys, types))
  h()
  if (e === null) {
    message.success('导入成功').then(null, null)
    hide()
  }
}

interface Props {
  id: string
  visible: boolean
  hide: () => void
  keys: Key[]
}

function Main ({ id, visible, hide, keys }: Props): ReactElement {
  const formRef = useRef<FormInstance>(null)
  useEffect(() => {
    const c = formRef.current
    if (!visible && c !== null) {
      c.resetFields()
    }
  }, [visible, formRef])
  return (
    <Modal title='选择统计范围' visible={visible} onCancel={hide} onOk={() => formRef.current?.submit()} maskClosable={false} destroyOnClose>
      <Form ref={formRef} onFinish={async d => await submitHandle(id, keys, d.type, hide)}>
        <Item name='type' label='统计范围' rules={[{ required: true, message: '请选择统计范围' }]}>
          <Checkbox.Group options={options}></Checkbox.Group>
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
